#include "../inc/myEventManager.h"
#include "../inc/myMacro.h"
#include "../inc/myApplet.h"
#include "../inc/skyTimer.h"
namespace Sky
{
	using namespace Sky;

	TResult myMsgMgr::dispatchSendEvent( Msg* msg )
	{
		getApplication()->getWindowMgr().handleSendEvent(this,msg);
		return vSuccess;
	}
	
	myMsgMgr::myMsgMgr():m_CallBack(vNull),_Timer(vNull)
	{
			
	}
	myMsgMgr::~myMsgMgr()
	{
		if(_Timer)
		{
			delete _Timer;
		}
	}
	
	Timer& myMsgMgr::getTimer()
	{
		if(_Timer == vNull)
		{
			_Timer = new Timer();
			_Timer->CreateTimer(10,Timer::TimerCallback(this,&myMsgMgr::handleTimer));
		}
		xAssert(_Timer);
		return *_Timer;
	}
	Void   myMsgMgr::deleteTimer(Handler::Delegate cb)
	{
		CBList::iterator itr = _list.getHead();
		const CallbackNode* node;
		CallbackNode* pNode;
		for(; itr != vNull; ++itr)
		{
			node = itr;
			pNode = const_cast<CallbackNode*>(node);
			if(pNode->_cb == cb)
			{
				_list.remove(*itr);
			}
		}
	}
	Bool myMsgMgr::getQueuedMessage(Msg* event)
	{
		return(m_EventQueue.out(event));
	}

	myApplet* myMsgMgr::getApplication()
	{
		TreeNode* node = this->getParent();
		while(node)
		{
			if(node->isKindOf(myApplet::Class))
				return (myApplet*)node;
			node = node->getParent();
		}
		return vNull;
	}

	Sky::NType::Bool myMsgMgr::createTimer( Handler::Delegate cb,u32 internal,Bool bRepeat /*= vTrue*/ )
	{
		getTimer();
		CallbackNode node;
		node._bRepeat = bRepeat;
		node._cb = cb;
		node._interal = internal;
		node._left = internal;
		return _list.append(node);
	}

	Sky::NValue::MsgStatus myMsgMgr::callSystem( Msg* message )
	{
		return m_CallBack(this,message);
	}

	Sky::NType::Void myMsgMgr::handleTimer()
	{
		List<CallbackNode>::iterator itr(_list.getHead());
		const CallbackNode* node;
		CallbackNode* pNode;
		for(; itr != vNull;)
		{
			node = itr;
			pNode = const_cast<CallbackNode*>(node);
			pNode->_left --;
			if(pNode->_left == 0)
			{
				(pNode->_cb)(this,vNull);
				if(pNode->_bRepeat)
					pNode->_left = pNode->_interal;
				else
					_list.remove(*itr);
			}
			++itr;
		}
	}

}
